package ele_handler

import (
	"fmt"
	"go-yuque/logger"
	"golang.org/x/net/html"
	"strings"
)

func init() {
	registerInitFunc(
		func() YuqueElementHandler {
			h := &bookMarkLinkStruct{}
			h.elements = []string{"card"}
			h.attributes = map[string]string{"name": "bookmarklink"}
			return h
		})
}

type bookMarkLinkStruct struct {
	BaseHandler
	Mode   string `json:"mode"`
	Src    string `json:"src"`
	Text   string `json:"text"`
	Detail struct {
		Icon      string      `json:"icon"`
		Image     string      `json:"image"`
		Title     string      `json:"title"`
		Belong    string      `json:"belong"`
		BelongURL interface{} `json:"belong_url"`
		Desc      string      `json:"desc"`
		URL       string      `json:"url"`
		Extra     struct {
		} `json:"extra"`
		Serializer string `json:"_serializer"`
	} `json:"detail"`
	Spacing string `json:"__spacing"`
	ID      string `json:"id"`
	Margin  struct {
		Top    bool `json:"top"`
		Bottom bool `json:"bottom"`
	} `json:"margin"`
}

func (b *bookMarkLinkStruct) doHandle() error {
	err := parseCardJson(b.node, b)
	if err != nil {
		logger.Errorf("[bookMarkLink]解析异常")
		sb := strings.Builder{}
		err := html.Render(&sb, b.node)
		if err != nil {
			b.WriteTextContext(sb.String())
		}
		return err
	}

	title := ""
	srcUrl := ""

	mode := b.Mode
	switch mode {
	case "card":
		// 卡片链接
		if len(b.Detail.Title) > 0 {
			title = b.Detail.Title
		} else {
			title = b.Text
		}

		if len(b.Detail.URL) > 0 {
			srcUrl = b.Detail.URL
		} else {
			srcUrl = b.Src
		}
	default:
		logger.Errorf("bookmarklink mode 未适配:%s", mode)
	}

	b.WriteTextContext(fmt.Sprintf("[%s](%s)\n", title, srcUrl))

	return nil
}
